import React,{Component} from 'react';
import {View, Text, StyleSheet, TouchableOpacity, ScrollView, PermissionsAndroid, Platform} from 'react-native'

import MyBle from './bluetooth'

async function requestBluetoothPermission  () {
  if (Platform.OS === 'ios') {
    return true
  }
  if (Platform.OS === 'android' && PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION) {
    const apiLevel = parseInt(Platform.Version.toString(), 10)
    console.log(`api level ${apiLevel}`)
    if (apiLevel < 31) {
      const granted = await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION)
      return granted === PermissionsAndroid.RESULTS.GRANTED
    }
    if (PermissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN && PermissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT) {
      console.log('申请蓝牙权限')
      const result = await PermissionsAndroid.requestMultiple([
        PermissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN,
        PermissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT,
        PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION
      ])
      console.log(`scan返回的${result['android.permission.BLUETOOTH_SCAN']}`)
      return (
        result['android.permission.BLUETOOTH_SCAN'] === PermissionsAndroid.RESULTS.GRANTED &&
        result['android.permission.BLUETOOTH_CONNECT'] === PermissionsAndroid.RESULTS.GRANTED &&
        result['android.permission.ACCESS_FINE_LOCATION'] === PermissionsAndroid.RESULTS.GRANTED
      )
    }
  }

  return false
}

class BluetoothManage extends Component {
  constructor(props: any) {
      super(props);
      this.state = {
          isShow: false,
          device_list: [],
      }

  }

  async componentDidMount() {
      if (Platform.OS === "android" && !(await requestBluetoothPermission())) {
          console.log('没有获取到权限')
          return;
      }
    
      await MyBle.Init()
      
      // this.searchName = 'unkown'
      // this.searchName = 'DRX'
    //   await MyBle.SearchBle(this.searchName, (data) => {
    //       console.log('蓝牙搜索到的===', data)
    //       this.setState({
    //           device_list: data
    //       })
    //   }, (err) => {
    //       console.log('搜索失败===', err)
    //   }, 5000)
  }

  research() {
      MyBle.SearchBle(this.searchName, (data) => {
          console.log('蓝牙搜索到的===', data)
          this.setState({
              device_list: data
          })
      }, (err) => {
          console.log('搜索失败===', err)
      }, 5000)
  }

  disconnect() {
      MyBle.DisconnectBle()
  }

  connect(item, id) {
    console.log(`准备连接${item.id}`)
      MyBle.ConnectBle(item.id, (device) => {
          console.log('连接成功',device)
      }, err => {
          console.log('连接失败===', err)
      })
  }

  send(item) {
      MyBle.BleWrite(item.order, (data) => {
          console.log('蓝牙页面数据返回===', data)
          switch (item.title) {
              case '开':
                  console.log('开了');
                  this.setState({openData: data});
                  break;
              case '关':
                  console.log('关了');
                  this.setState({openData: data});
                  break;
              case '红':
                  console.log('红');
                  this.setState({openData: data});
                  break;
              case '蓝':
                  console.log('蓝');
                  this.setState({openData: data});
                  break;
          }
      }, (err) => {
          console.log('写入失败===', err)
      })
  }


  render() {
      return (
          <View style={{flex: 1,}}>
              <ScrollView>
                  <Text style={{color: '#333'}}>
                      蓝牙manage页面
                  </Text>
                  <View style={styles.title}>
                      <Text style={{color: '#FFF'}}>
                          蓝牙列表
                      </Text>
                  </View>

                  <TouchableOpacity onPress={() => this.research()} style={[styles.title, {backgroundColor: '#fff'}]}>
                      <Text style={{color: '#333'}}>
                          重新搜索
                      </Text>
                  </TouchableOpacity>
                  {
                      this.state.device_list.map((item, id) => {
                          return (
                              <View key={id} style={styles.bleItem}>
                                  <View>
                                      <Text style={{color: '#333'}}>name:{item.name}</Text>
                                      <Text style={{color: '#333'}}>mac:{item.id}</Text>
                                      <Text style={{color: '#333'}}>isConnectable:{item.isConnectable}</Text>
                                  </View>
                                  <View style={{justifyContent: 'center', alignItems: 'center'}}>
                                      <TouchableOpacity onPress={() => this.connect(item)} style={styles.connectBtn}>
                                          <Text style={{color: 'red'}}>连接</Text>
                                      </TouchableOpacity>
                                      <TouchableOpacity onPress={() => this.disconnect(item)}
                                                        style={styles.connectBtn}>
                                          <Text style={{color: 'blue'}}>断开连接</Text>
                                      </TouchableOpacity>
                                  </View>
                              </View>
                          )
                      })
                  }
                  {
                      [
                          {order: '5500000002050005AA', title: '开'},
                          {order: '5500000002050106AA', title: '关'},
                          {order: '55000000040100ff0000AA', title: '红'},
                          {order: '550000000401ff000000AA', title: '蓝'},
                      ].map((item, id) => {
                          return (
                              <TouchableOpacity key={id} onPress={() => this.send(item)} style={styles.btn}>
                                  <Text style={{color: 'blue'}}>{item.title}</Text>
                              </TouchableOpacity>
                          )
                      })
                  }
              </ScrollView>
          </View>
      );
  }

  componentWillUnmount() {
      MyBle.DisconnectBle()
  }
}

const styles = StyleSheet.create({
  sectionContainer: {
    marginTop: 32,
    paddingHorizontal: 24,
  },
  sectionTitle: {
    fontSize: 24,
    fontWeight: '600',
  },
  sectionDescription: {
    marginTop: 8,
    fontSize: 18,
    fontWeight: '400',
  },
  highlight: {
    fontWeight: '700',
  },
});

export default BluetoothManage;
